package com.heima.search.service.impl;

import com.heima.commom.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author by jojo
 * @Date 2022/3/16
 * @Description
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     *
     * @param dto
     */
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO dto) {
        String words = dto.getSearchWords();
        Integer equipmentId = dto.getEquipmentId();
        //远程查询行为实体类
        ResponseResult<ApBehaviorEntry> entryResult = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), equipmentId);
        if (!entryResult.checkCode()) {
            log.error("远程查询行为实体类失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询行为实体类失败");
        }
        ApBehaviorEntry entry = entryResult.getData();
        if (entry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体数据不存在！！");
        }
        // 判断历史记录是否存在
        Query query = Query.query(Criteria.where("entryId").is(entry.getId()).and("keyword").is(words));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        // 如果存在历史记录  更新 创建时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        userSearch = new ApUserSearch();
        userSearch.setEntryId(entry.getId());
        userSearch.setKeyword(words);
        userSearch.setCreatedTime(new Date());
        mongoTemplate.save(userSearch);
    }

    /**
     * 默认加载10条数据，按照时间倒序
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        Integer equipmentId = dto.getEquipmentId();
        ApUser apUser = AppThreadLocalUtils.getUser();
        //1.用户id或者设备id远程查询行为实体类
        ResponseResult<ApBehaviorEntry> entryResult = behaviorFeign.findByUserIdOrEquipmentId(apUser.getId(), equipmentId);
        if (!entryResult.checkCode()) {
            log.error("远程查询行为实体类失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询行为实体类失败");
        }
        ApBehaviorEntry entry = entryResult.getData();
        if (entry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体数据不存在！！");
        }
        // 2. 根据行为实体id  按照创建时间降序排序  查询最近10条搜索历史记录
        int size=10;
        Query query = Query.query(Criteria.where("entryId").is(entry.getId()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(size);
        List<ApUserSearch> searchList = mongoTemplate.find(query, ApUserSearch.class);
        //3.返回数据
        return ResponseResult.okResult(searchList);
    }

    /**
     删除搜索历史
     @param dto
     @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        //获取登录用户
        ApUser apUser = AppThreadLocalUtils.getUser();
        //1.用户id或者设备id远程查询行为实体类
        ResponseResult<ApBehaviorEntry> entryResult = behaviorFeign.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        if (!entryResult.checkCode()) {
            log.error("远程查询行为实体类失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询行为实体类失败");
        }
        ApBehaviorEntry entry = entryResult.getData();
        if (entry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体数据不存在！！");
        }
        //根据搜索信息表的id和行为实体id删除记录
        Query query = Query.query(Criteria.where("id").is(dto.getId()).and("entryId").is(entry.getId()));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
